package com.opoc.utils;

import org.springframework.web.multipart.MultipartFile;
import org.apache.commons.compress.utils.IOUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.UUID;

public class FileUtils {
  public static final String ROOT_FILE_PATH = System.getProperty("user.dir").replaceAll("\\\\","/") + "/src/main/resources/static/files/";
  public static final String IMAGE_FILE_PATH = ROOT_FILE_PATH+ "images/";
  public static final String FILE_PATH = ROOT_FILE_PATH+ "files/";
  public static final String EMPTY = "";
  private static final String POINT = ".";

  /**
   * 生成远程访问的url
   */
  public static String getURLFromPath(String filePath){
    System.out.println(ROOT_FILE_PATH);
    if (filePath == null) {
      return null;
    }
    return  "http://localhost:8080/" + filePath.replace(ROOT_FILE_PATH, "");
  }

  /**
   * 获取文件后缀名
   *
   */
  public static String getFileExtension(MultipartFile file){
    if (file == null){
      return null;
    }
    String fileName = file.getOriginalFilename();
    //如果没有文件名或者文件名为空
    if (fileName == null || EMPTY.equals(fileName.trim())){
      return EMPTY;
    }
    //如果文件名中包含.取最后一个点的后缀
    if (fileName.contains(POINT)){
      return fileName.substring(fileName.lastIndexOf(POINT) + 1);
    }
    return EMPTY;
  }

  public static String getFileExtension(String fileName){
    //如果没有文件名或者文件名为空
    if (fileName == null || EMPTY.equals(fileName.trim())){
      return EMPTY;
    }
    //如果文件名中包含.取最后一个点的后缀
    if (fileName.contains(POINT)){
      return fileName.substring(fileName.lastIndexOf(POINT) + 1);
    }
    return EMPTY;
  }


  public static String uploadFile(MultipartFile file) {
    if (file == null){
      return null;
    }

    File dir = new File(IMAGE_FILE_PATH);
    //如果目录不存在，则创建
    if (!dir.exists()) {
      dir.mkdirs();
    }

    System.out.println("文件上传，保存的位置:" + IMAGE_FILE_PATH);

    //新文件名
    String fileDirectory = IMAGE_FILE_PATH + UUID.randomUUID().toString().replaceAll("-", "") + POINT + getFileExtension(file);
    File newFile = new File(fileDirectory);

    System.out.println(fileDirectory);
    //复制操作
    try {
      file.transferTo(newFile);
      //返回文件存储路径
      return fileDirectory;
    } catch ( IOException e) {
      e.printStackTrace();
      return null;
    }
  }

 public static String uploadFiles(MultipartFile file, String company_name) {

    if (file == null){
      return null;
    }

    File dir = new File(FILE_PATH);
    //如果目录不存在，则创建
    if (!dir.exists()) {
      dir.mkdirs();
    }

    System.out.println("文件上传，保存的位置:" + FILE_PATH);

    //新文件名
    String fileDirectory=FILE_PATH+"检测检验报告-"+company_name+ POINT + getFileExtension(file);
    File newFile = new File(fileDirectory);

    System.out.println(fileDirectory);
    //复制操作
    try {
      file.transferTo(newFile);
      //返回文件存储路径
      return fileDirectory;
    } catch ( IOException e) {
      e.printStackTrace();
      return null;
    }
  }

  /**
   *bytes对象转File对象 返回存储路径
   */
  public static String BytesSaveAsFile(byte[] bytes, String filename) throws IOException {
    String FilePath = IMAGE_FILE_PATH + UUID.randomUUID().toString().replaceAll("-", "") + POINT + getFileExtension(filename);
    File dir = new File(IMAGE_FILE_PATH);
    //如果目录不存在，则创建
    if (!dir.exists()) {
      dir.mkdirs();
    }
    File localFile = new File(FilePath);
    // 输出流
    OutputStream os = Files.newOutputStream(localFile.toPath());
    os.write(bytes);
    os.close();
    return FilePath;
  }

  /**
   * 把字节流转换为base64格式存储
   */
  public static String BytesToBase64(byte[] bytes){
    Base64.Encoder encoder = Base64.getEncoder();
    return encoder.encodeToString(bytes);
  }

  /**
   *把base64文件转换为字节流
   */
  public static byte[] Base64ToBytes(String base64){
    Base64.Decoder decoder = Base64.getDecoder();
    return decoder.decode(base64);
  }

  /**
   *根据路径删除文件 成功返回true
   */
  public static boolean deleteFile(String path){
    if (path == null){
      return false;
    }
    File file = new File(path);
    if (file.isFile() && file.exists()){
      return file.delete();
    }
    return false;
  }

    /**
     * 根据地址获得数据的输入流
     * @param strUrl 网络连接地址
     * @return url的输入流
     */
    public static InputStream getInputStreamByUrl(String strUrl){
        HttpURLConnection conn = null;
        try {
            String[] parts = strUrl.split("/", 5); // 拆分URL，以便仅编码路径部分
            String encodedPath = URLEncoder.encode(parts[4], "UTF-8");
            String encodedUrl = parts[0] + "/" + parts[1] + "/" + parts[2] + "/" + parts[3]+"/"+encodedPath;
            System.out.println(encodedUrl);
            URL url = new URL(encodedUrl);
            conn = (HttpURLConnection)url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(20 * 1000);
            final ByteArrayOutputStream output = new ByteArrayOutputStream();
            IOUtils.copy(conn.getInputStream(),output);
            return  new ByteArrayInputStream(output.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try{
                if (conn != null) {
                    conn.disconnect();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return null;
    }

    /*
    * 下载文件
    * */
    public static ResponseEntity<byte[]> downloadFileByUrl(String downUrl, String fileName) throws IOException {
        InputStream inputStream = getInputStreamByUrl(downUrl);

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        IOUtils.copy(inputStream, byteArrayOutputStream);
        inputStream.close();
        HttpHeaders headers = new HttpHeaders();
        //设置下载协议头。下面fileName的两次转换主要是为了保证中文文件名
        fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        headers.set(HttpHeaders.CONTENT_DISPOSITION,"filename=" + new String(fileName.getBytes(), "utf-8"));
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(byteArrayOutputStream.toByteArray(), headers, HttpStatus.OK);
        byteArrayOutputStream.close();
        return responseEntity;

    }

    /**
     * 获取文件名
     */
    public static String getFilename(String urlString) throws MalformedURLException {
        URL url = new URL(urlString);

        String path = url.getPath();
        String[] pathSegments = path.split("/");
        String fileNameWithExtension = pathSegments[pathSegments.length - 1];

        // 去除扩展名
        int lastDotIndex = fileNameWithExtension.lastIndexOf(".");
        String fileNameWithoutExtension = (lastDotIndex != -1) ? fileNameWithExtension.substring(0, lastDotIndex) : fileNameWithExtension;

        System.out.println("Document Name without Extension: " + fileNameWithoutExtension);
        return fileNameWithExtension;
    }
    public static String generateUniqueURL(String originalURL) {
        try {
            // 使用 SHA-256 哈希算法生成唯一标识符
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            byte[] hash = md.digest(originalURL.getBytes());

            // 将哈希值编码为 Base64 格式的字符串
            String uniqueID = Base64.getEncoder().encodeToString(hash);

            // 构建唯一URL
            String uniqueURL = FILE_PATH + uniqueID + ".docx";

            return uniqueURL;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

}